package com.chushouya.manager.service.api.impl;

import com.chushouya.common.support.Contexts;
import com.chushouya.manager.dao.entity.SuggestEntity;
import com.chushouya.manager.dao.entity.UserEntity;
import com.chushouya.manager.dao.repository.SuggestRepository;
import com.chushouya.manager.dao.repository.UserRepository;
import com.chushouya.manager.dto.api.suggest.FeedbackDTO;
import com.chushouya.manager.service.api.SuggestApiService;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Beans;
import com.general.framework.core.lang.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * 反馈建议接口服务实现类
 * 提供用户反馈相关功能
 * 
 * @author chushouya
 */
@Service
@Slf4j
public class SuggestApiServiceImpl implements SuggestApiService {

    @Resource
    private SuggestRepository suggestRepository;

    @Resource
    private UserRepository userRepository;

    @Override
    public Long submitFeedback(FeedbackDTO feedbackDTO) {
        // 获取当前用户ID
        final Long userId = Contexts.getUserContext().getUserId();
        
        // 参数校验
        if (Objects.isNull(userId)) {
            throw Ex.business("用户ID不能为空");
        }
        
        if (Objects.isNull(feedbackDTO) || Strings.isBlank(feedbackDTO.getSuggestContent())) {
            throw Ex.business("反馈内容不能为空");
        }

        // 查询用户信息
        UserEntity userEntity = userRepository.selectByPrimaryKey(userId);
        if (Objects.isNull(userEntity)) {
            throw Ex.business("用户不存在");
        }

        // 构建反馈实体
        SuggestEntity suggest = Beans.copy(feedbackDTO, SuggestEntity.class);
        suggest.setUserId(userId);
        suggest.setUserName(userEntity.getUserName());
        suggest.setUserType(userEntity.getUserType());
        suggest.setCreateTime(new Date());
        suggest.setHandleStatus(0); // 0-未处理

        // 保存反馈
        suggestRepository.saveSuggest(suggest);
        
        log.info("用户反馈提交成功, userId={}, suggestId={}, content={}", 
                userId, suggest.getSuggestId(), feedbackDTO.getSuggestContent());

        return suggest.getSuggestId();
    }
}
